"""
工具函数模块
包含各种辅助功能
"""
import numpy as np
from scipy.interpolate import interp1d
from typing import List, Dict, Any, Tuple
import matplotlib.pyplot as plt

# 假设这些变量在主程序中定义或从外部导入
# type_match_list = []
# w1, w2, w3, w4, w5, w6 = 0.16, 0.09, 0.47, 0.28, 0, 0

def calculate_match_degree(vehicle_attr: Tuple, cargo_attr: Tuple,
                          real_data: Dict[str, List], w1: float, w2: float,
                          w3: float, w4: float, w5: float, w6: float) -> List[float]:
    """
    计算车辆与货物的匹配度

    参数:
        vehicle_attr: 车辆属性
        cargo_attr: 货物属性
        real_data: 真实数据字典
        w1-w6: 各匹配指标权重

    返回:
        匹配度列表
    """
    global type_match_list

    vehicle_type = vehicle_attr[0]
    cargo_type = cargo_attr[0]

    # 类型匹配度
    type_match = 0
    for item in type_match_list:
        if item[0] == vehicle_type and item[1] == cargo_type:
            type_match = item[2]
            break

    # 其他属性匹配度计算...
    # 这里简化处理，实际应根据具体逻辑计算
    attr_match = 0.5
    load_match = 0.6
    flow_match = 0.7
    time_match = 0.8
    price_match = 0.9

    # 综合匹配度
    doubleS = (w1 * attr_match + w2 * type_match + w3 * load_match +
               w4 * flow_match + w5 * time_match + w6 * price_match)

    return [doubleS, attr_match, type_match, load_match, flow_match, time_match, 0, 1]

def moving_average(data: List[float], window_size: int) -> np.ndarray:
    """
    计算移动平均值

    参数:
        data: 数据列表
        window_size: 窗口大小

    返回:
        移动平均后的数组
    """
    return np.convolve(data, np.ones(window_size) / window_size, mode='valid')

def interpolate_data(data: List[float], new_length: int) -> np.ndarray:
    """
    插值扩充数据

    参数:
        data: 原始数据
        new_length: 新数据长度

    返回:
        插值后的数组
    """
    original_length = len(data)
    new_indices = np.linspace(0, original_length - 1, new_length)
    interpolator = interp1d(np.arange(original_length), data, kind='linear')
    return interpolator(new_indices)

def moving_average(data, window_size):
    """
    平滑函数
    :param data:
    :param window_size:
    :return:
    """
    if window_size <= 0:
        raise ValueError("Window size should be greater than 0.")

    if window_size > len(data):
        raise ValueError("Window size should not be greater than the length of data.")

    # Cumulative sum of data elements
    cumsum = [0]
    for i, x in enumerate(data):
        cumsum.append(cumsum[i] + x)

    # Compute moving averages
    ma_values = []
    for i in range(len(data) - window_size + 1):
        average = (cumsum[i + window_size] - cumsum[i]) / window_size
        ma_values.append(average)

    return ma_values


def plot_data(data, title="Data Plot", x_label="X-axis", y_label="Y-axis"):
    """
    画图
    :param data:
    :param title:
    :param x_label:
    :param y_label:
    :return:

    Plots a simple line graph based on the provided data.

    Parameters:
    - data (list): A list of integers or floats to be plotted.
    - title (str): The title of the plot.
    - x_label (str): The label for the x-axis.
    - y_label (str): The label for the y-axis.
    """
    plt.figure(figsize=(10, 5))  # Set the figure size
    plt.plot(data)  # Plot the data
    plt.title(title)  # Set the title
    plt.xlabel(x_label)  # Set x-axis label
    plt.ylabel(y_label)  # Set y-axis label
    plt.grid(True, which='both', linestyle='--', linewidth=0.5)  # Add a grid
    plt.tight_layout()  # Adjust subplot parameters to give specified padding
    plt.show()


def rolling_average(lst, window_size=4):
    # 确保列表长度能被窗口大小整除，如果不是则需要截断部分数据

    if len(lst) % window_size != 0:
        lst = lst[:-(len(lst) % window_size)]

    # 创建一个新的空列表存放平均值

    averages_list = []

    # 按窗口大小滑动并计算平均值

    for i in range(0, len(lst), window_size):
        window = lst[i:i + window_size]

        average = sum(window) / window_size

        averages_list.append(average)

    return averages_list

